import { message } from "antd"
import { FC } from "react"
import { Redirect, Route, RouteProps } from "react-router-dom"
import useLoginModel from "../../model/useLoginModel"
import { pathName } from "../../routes/path"

interface PrivateRouteProps extends RouteProps {
    component: React.ComponentType<any>
}

const noPermissionPaths: Array<string> = [pathName.DASHBOARD, pathName.DEFAULT]
const noLoginPaths: Array<string> = [pathName.LOGIN]

const checkPermissions = (menuResource: Array<string | null> | undefined, path: string): boolean => {
    return Array.isArray(menuResource) && menuResource.includes(path)
}

const PermissionRoute: FC<PrivateRouteProps> = ({ component: Componment, ...rest }) => {
    const user = useLoginModel()
    return <Route {...rest} render={props => {
        const path = rest.path as string
        const menuResource = user.permissions?.menuResource
        if (noLoginPaths.includes(path)) return <Componment {...props} /> //无需登录页面直接显示
        if (user.token) {
            if (noPermissionPaths.includes(path)) return <Componment {...props} /> //无需权限页面登录即可显示
            if (checkPermissions(menuResource, path)) return <Componment {...props} /> //需要权限的页面校验通过后展示
            message.error('您没有权限访问当前页面')
        } else {
            if (!noLoginPaths.includes(path) && !noPermissionPaths.includes(path)) message.error('您需要先登录系统')
        }
        return <Redirect to={pathName.LOGIN} />
    }} />
}

export default PermissionRoute